<script setup>
import {reactive} from 'vue';

const props = defineProps({
    servePort:String,
    serveUrl:String,
    cell:Object,
    form:Object,
    cellIndex:String,
    cellMap:Object
})

const state = reactive({
    options:[]
})
function parseTemplate(templateStr,cellMap) {
    return templateStr.replace(/\$\{(\w+)\}/g, (match, cellIndex) => {
        const cell = cellMap[props.cellIndex]
        // 空值处理三部曲
        if (!cell) return 'null';                   // 情况1：单元格不存在
        if (cell.value === '') return '""';          // 情况2：显式空字符串
        if (cell.value == null) return 'null';      // 情况3：null/undefined
        
        // 常规类型处理
        return typeof cell.value === 'string' 
        ? `"${cell.value}"` 
        : cell.value;
    });
}

const getOptsByApi = async ()=>{
    let apiType = props.cell.optionsApiType || 'GET';
    let params = parseTemplate(props.cell.optionsApiParams,props.cellMap);
    console.log(params,'params____++++');
    const response = await fetch('/api'+props.cell.optionsApiUrl,{
        method:apiType,
        body:params,
        headers:{
            'Content-Type':'application/json'
        }
    }).then(res=>{
        return res.json();
    });
    let data = [];
    response.data.map(item=>{
        data.push({
            label:item[props.cell.optionsApiLabel],
            value:item[props.cell.optionsApiValue]
        })
    })
    state.options = data
}


const getOpts = ()=>{
    if(props.cell.optionsDataType=='api'){
        getOptsByApi();
    }else if(props.cell.optionsDataType=='static'){
        state.options = JSON.parse(props.cell.staticOptsData)
    }else if(props.cell.optionsDataType=='dict'){
        console.log('字典数据');
    }
}
const changeSelect = (v)=>{
    props.form[props.cell.__vModel__] = v;
    let label = state.options.find(item=>{
        return item.value == v;
    }).label;
    props.form[props.cell.__vModel__+'Label'] = label

}
getOpts();
</script>
<template>
    <el-select v-model="props.form[props.cell.__vModel__]" @change="changeSelect">
        <el-option v-for="item in state.options" :label="item.label" :value="item.value"></el-option>
    </el-select>
</template>